package com.up4years.dataapi.service.weixin;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Arrays;
import java.util.Date;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import com.up4years.dataapi.entity.weixin.AccessToken;
import com.up4years.dataapi.entity.weixin.Button;
import com.up4years.dataapi.entity.weixin.Menu;
import com.up4years.dataapi.entity.weixin.OAuth2AccessToken;
import com.up4years.utils.CommonUtil;
import com.up4years.utils.HttpUtil;


/**
 * 微信工具类
 *
 */
public class WeixinService {

	/**access_token公众号调用各接口使用**/
	private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	/**使用oauth2.0接口获取token(该token)**/
	private static final String OAuth20_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	
	private static final String OAuth20_OPENID_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
	
	private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
	
	private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
	
	private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN";
	
	private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
	
	private static AccessToken accessToken = null;
	
	/**
	 * POST请求
	 * @param url
	 * @param outStr
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static JSONObject doPostStr(String url,String outStr) throws ParseException, IOException{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		JSONObject jsonObject = null;
		httpost.setEntity(new StringEntity(outStr,"UTF-8"));
		HttpResponse response = client.execute(httpost);
		String result = EntityUtils.toString(response.getEntity(),"UTF-8");
		jsonObject = JSONObject.fromObject(result);
		return jsonObject;
	}
	
	/**
	 * 文件上传
	 * @param filePath
	 * @param accessToken
	 * @param type
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws KeyManagementException
	 */
	public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		File file = new File(filePath);
		if (!file.exists() || !file.isFile()) {
			throw new IOException("文件不存在");
		}

		String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
		
		URL urlObj = new URL(url);
		//连接
		HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

		con.setRequestMethod("POST"); 
		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false); 

		//设置请求头信息
		con.setRequestProperty("Connection", "Keep-Alive");
		con.setRequestProperty("Charset", "UTF-8");

		//设置边界
		String BOUNDARY = "----------" + System.currentTimeMillis();
		con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		StringBuilder sb = new StringBuilder();
		sb.append("--");
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");

		byte[] head = sb.toString().getBytes("utf-8");

		//获得输出流
		OutputStream out = new DataOutputStream(con.getOutputStream());
		//输出表头
		out.write(head);

		//文件正文部分
		//把文件已流文件的方式 推入到url中
		DataInputStream in = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		in.close();

		//结尾部分
		byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线

		out.write(foot);

		out.flush();
		out.close();

		StringBuffer buffer = new StringBuffer();
		BufferedReader reader = null;
		String result = null;
		try {
			//定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
		}

		JSONObject jsonObj = JSONObject.fromObject(result);
		System.out.println(jsonObj);
		String typeName = "media_id";
		if(!"image".equals(type)){
			typeName = type + "_media_id";
		}
		String mediaId = jsonObj.getString(typeName);
		return mediaId;
	}
	
	/**
	 * 获取accessToken
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public synchronized static AccessToken getAccessToken() throws ParseException, IOException{
		//token未过期 则继续使用
		if(accessToken!=null&& accessToken.getExpiresIn()> new Date().getTime()){
			return accessToken;
		}
		AccessToken token = new AccessToken();
		String url = ACCESS_TOKEN_URL.replace("APPID", CommonUtil.getWEIXIN_APPID()).replace("APPSECRET", CommonUtil.getWEIXIN_APPSECRET());
		JSONObject jsonObject = JSONObject.fromObject(HttpUtil.requestGet(url));
		if(jsonObject!=null){
			token.setToken(jsonObject.getString("access_token"));
			token.setExpiresIn(jsonObject.getInt("expires_in"));
		}
		accessToken = token;
		return accessToken;
	}
	/**
	 * 获取accessToken
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static OAuth2AccessToken getOAuth20AccessToken(String code) throws ParseException, IOException{
		if(StringUtils.isBlank(code)){return null;}
		OAuth2AccessToken token = new OAuth2AccessToken();
		String url = OAuth20_ACCESS_TOKEN_URL.replace("APPID", CommonUtil.getWEIXIN_APPID()).replace("SECRET", CommonUtil.getWEIXIN_APPSECRET()).replace("CODE", code);
		JSONObject jsonObject = JSONObject.fromObject(HttpUtil.requestGet(url));
		if(jsonObject!=null){
			token.setAccess_token(jsonObject.getString("access_token"));
			token.setExpires_in(jsonObject.getInt("expires_in"));
			token.setOpenid(jsonObject.getString("openid"));
			token.setRefresh_token(jsonObject.getString("refresh_token"));
			token.setScope(jsonObject.getString("scope"));
		//	token.setUnionid(jsonObject.getString("unionid"));
		}
		return token;
	}
	/**
	 * 返回一个封装好的连接 配置在菜单中可以跳转
	 * @param jumpurl
	 * @param tourl
	 * @param useOpenid
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String generateURL(String jumpurl,String tourl,boolean useOpenid){
			if(useOpenid&&StringUtils.isNotBlank(tourl)){
 					try {
 						String result =  jumpurl +"?backURI=" +URLEncoder.encode(tourl, "UTF-8");
 						result = OAuth20_OPENID_URL.replace("APPID", CommonUtil.getWEIXIN_APPID()).replace("REDIRECT_URI", URLEncoder.encode(result, "UTF-8"));
 						
						return result;
					} catch (UnsupportedEncodingException e) {
 						e.printStackTrace();
					}
 			}else{
 				return tourl;
 			}
			return "";

 	}
	/**
	 * 组装菜单
	 * @return
	 */
	public static Menu initMenu(){
		Menu menu = new Menu();
		Button button11 = new Button();
		button11.setName("G3");
		button11.setType("view");
		button11.setUrl("https://fouryears.pagekite.me/index2.jsp");
		
		Button button21 = new Button();
		button21.setName("view菜单1");
		button21.setType("view");
		button21.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx472eeff76cce6d1d&redirect_uri=https%3A%2F%2Fxvxingan.pagekite.me%2Fxvxingan%2F&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");
		
		Button button31 = new Button();
		button31.setName("扫码事件");
		button31.setType("scancode_push");
		button31.setKey("31");
		
		Button button32 = new Button();
		button32.setName("地理位置");
		button32.setType("location_select");
		button32.setKey("32");
		
		Button button = new Button();
		button.setName("菜单test");
		
		button.setSub_button(Arrays.asList(button31,button32));
		menu.addButton(button11);
		menu.addButton(button21);
		menu.addButton(button);
		return menu;
	}
	
	public static int createMenu(String token,String menu) throws ParseException, IOException{
		int result = 0;
		String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = doPostStr(url, menu);
		if(jsonObject != null){
			result = jsonObject.getInt("errcode");
		}
		return result;
	}
	
	public static JSONObject queryMenu(String token) throws ParseException, IOException{
		String url = QUERY_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = JSONObject.fromObject(HttpUtil.requestGet(url));
		return jsonObject;
	}
	
	public static int deleteMenu(String token) throws ParseException, IOException{
		String url = DELETE_MENU_URL.replace("ACCESS_TOKEN", token);
		JSONObject jsonObject = JSONObject.fromObject(HttpUtil.requestGet(url));
		int result = 0;
		if(jsonObject != null){
			result = jsonObject.getInt("errcode");
		}
		return result;
	}
	@Test
	public void testGetAccessToken() throws ParseException, IOException{
 		System.out.println(getAccessToken().getToken());
	}
	@Test
	public void testCreateMenu() throws ParseException, IOException{
		JSONObject menus = JSONObject.fromObject(initMenu());
		System.out.println(createMenu("J5e1tLP4hOAsP-DEc1l74NDvXdg0A84L0gOwLOqpGaOWo2_4Gvunc3P5LLnHdBjGF3UpXTz6CtPFmCHxTBQWMInoHmGL73jjOM3ecbVOUTEDXRfADAQKE",menus.toString()));
	}
}
